package cn.edu.njust.alg.leetcode;

import java.util.Stack;

public class Leetcode_224_Basic_Calculator {
	public static int calc(int op1, int op2, boolean isplus) {
		if (isplus)
			return op1 + op2;
		else
			return op1 - op2;
	}

	public static int calculate(String s) {
		int op1 = 0, op2 = 0;
		boolean isplus = true;
		Stack<Integer> stack = new Stack<Integer>();
		Stack<Boolean> ops = new Stack<Boolean>();
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			if (c == ' ') {
				continue;
			}
			switch (c) {
			case '+':
				op1 = calc(op1, op2, isplus);
				op2 = 0;
				isplus = true;
				break;
			case '-':
				op1 = calc(op1, op2, isplus);
				op2 = 0;
				isplus = false;
				break;
			case '(':
				stack.push(op1);
				ops.push(isplus);
				op1 = 0;
				isplus = true;
				break;
			case ')':
				op2 = calc(op1, op2, isplus);
				op1 = stack.pop();
				isplus = ops.pop();
				break;
			default:
				op2 = op2 * 10 + (c - '0');
				break;
			}
		}
		int res = calc(op1, op2, isplus);
		return res;
	}

	public static void main(String[] args) {

		System.out.println(calculate("10 - (1 +3)"));
	}

}
